<script lang="ts" setup>
  import { computed, onMounted, reactive, Ref, ref } from 'vue';
  import useLoading from '@/hooks/loading';
  import {
    Message,
    PaginationProps,
    TableColumnData,
  } from '@arco-design/web-vue';
  import {
    selectPageOperationLog,
    statisOperationLog,
  } from '@/api/operationlog';
  import { EChartsOption, SeriesOption } from 'echarts';

  const { loading, setLoading } = useLoading(true);
  const operationTypeFieldNames = { value: 'value', label: 'label' };
  const operationTypeOptions = ref([
    {
      label: '全部',
      value: '',
    },
    {
      label: '查询',
      value: '查询',
    },
    {
      label: '新增',
      value: '新增',
    },
    {
      label: '修改',
      value: '修改',
    },
    {
      label: '删除',
      value: '删除',
    },
  ]);
  const methodTypeFieldNames = { value: 'value', label: 'label' };
  const methodTypeOptions = ref([
    {
      label: '全部',
      value: '',
    },
    {
      label: 'POST',
      value: 'POST',
    },
    {
      label: 'GET',
      value: 'GET',
    },
    {
      label: 'DELETE',
      value: 'DELETE',
    },
    {
      label: 'PUT',
      value: 'PUT',
    },
  ]);
  const params = ref({
    pageNo: 1,
    pageSize: 10,
    operationName: '',
    operationType: '',
    methodType: '',
  });
  const operationLogList = ref([]);
  const pagination = reactive<PaginationProps>({
    showTotal: true,
    showPageSize: true,
    pageSizeOptions: [5, 10, 50, 100],
  });
  const option: Ref<EChartsOption> = ref({
    title: {
      text: '一周日志统计',
    },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['成功', '失败'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: (function () {
        const dates: string[] = [];
        for (let i = 6; i >= 0; i -= 1) {
          const date = new Date(new Date());
          date.setDate(new Date().getDate() - i);
          dates.push(date.toISOString().split('T')[0]);
        }
        return dates;
      })(),
    },
    yAxis: {
      type: 'value',
      scale: true,
      boundaryGap: ['0%', '10%'],
    },
    series: [
      {
        name: '成功',
        type: 'line',
        stack: 'Total1',
        smooth: true,
        itemStyle: {
          color: '#165DFF',
        },
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' },
          ],
        },
        markLine: {
          data: [{ type: 'average', name: 'Avg' }],
        },
      },
      {
        name: '失败',
        type: 'line',
        stack: 'Total2',
        smooth: true,
        itemStyle: {
          color: '#F53F3F',
        },
        data: [],
        markPoint: {
          data: [
            { type: 'max', name: 'Max' },
            { type: 'min', name: 'Min' },
          ],
        },
        markLine: {
          data: [{ type: 'average', name: 'Avg' }],
        },
      },
    ],
  });
  // 信息列表
  const columns: TableColumnData[] = [
    {
      title: '操作人',
      dataIndex: 'username',
      align: 'center',
      tooltip: true,
      ellipsis: true, // 超出内容显示省略号
    },
    {
      title: '操作名称',
      dataIndex: 'operationName',
      align: 'center',
      tooltip: true,
      ellipsis: true, // 超出内容显示省略号
    },
    {
      title: '操作类型',
      dataIndex: 'operationType',
      align: 'center',
      tooltip: true,
      ellipsis: true, // 超出内容显示省略号
    },
    {
      title: '请求方式',
      dataIndex: 'methodType',
      align: 'center',
      tooltip: true,
      ellipsis: true,
      slotName: 'methodType',
    },
    {
      title: 'URL',
      dataIndex: 'url',
      align: 'center',
      tooltip: true,
      ellipsis: true,
    },
    {
      title: 'IP地址',
      dataIndex: 'ip',
      align: 'center',
    },
    {
      title: '执行状态',
      dataIndex: 'status',
      align: 'center',
      slotName: 'status',
    },
    {
      title: '操作时间',
      dataIndex: 'timestamp',
      align: 'center',
    },
    {
      title: '操作',
      align: 'center',
      slotName: 'operation',
      width: 250,
    },
  ];
  const getOperationLogList = async () => {
    setLoading(true);
    try {
      const result = await selectPageOperationLog(params.value);
      operationLogList.value = result.data.list;
      pagination.total = result.data.total;
      pagination.current = params.value.pageNo;
      pagination.pageSize = params.value.pageSize;
    } finally {
      setLoading(false);
    }
  };
  const getStatisOperationLog = async () => {
    const result = await statisOperationLog();
    if (option.value.series) {
      (option.value.series as SeriesOption[])[0].data = result.data.success;
      (option.value.series as SeriesOption[])[1].data = result.data.failure;
    }
  };
  getOperationLogList();
  onMounted(() => {
    // 初始化图表
    getStatisOperationLog();
  });
  // 查询
  const handleSearch = () => {
    params.value.pageNo = 1;
    getOperationLogList();
  };
  // 重置
  const handleReset = () => {
    params.value.pageNo = 1;
    params.value.operationName = '';
    params.value.operationType = '';
    params.value.methodType = '';
    getOperationLogList();
  };
  // 切换页面
  const handlePageNoChange = (pageNo: number) => {
    params.value.pageNo = pageNo;
    getOperationLogList();
  };
  // 变更页数数量
  const handlePageSizeChange = (pageSize: number) => {
    params.value.pageSize = pageSize;
    getOperationLogList();
  };
  // 删除
  const handleDelete = async (key: string) => {
    Message.success('删除成功');
    // 重新查询
    if (operationLogList.value.length === 1 && params.value.pageNo !== 1) {
      params.value.pageNo -= 1;
    }
    await getOperationLogList();
  };
  const handleEdit = async (id: number) => {};
</script>

<template>
  <a-row style="margin-bottom: 6px">
    <a-col :span="24">
      <Chart :option="option" height="300px" />
    </a-col>
  </a-row>
  <a-divider style="margin-top: 10px; margin-bottom: 16px" />
  <a-row>
    <a-col :flex="1">
      <a-form
        :model="params"
        label-align="left"
        :label-col-props="{ span: 6 }"
        layout="inline"
        :wrapper-col-props="{ span: 18 }"
      >
        <a-form-item field="operationName" label="操作名称：">
          <a-input
            v-model="params.operationName"
            placeholder="请输入操作名称"
          />
        </a-form-item>
        <a-form-item field="operationType" label="操作类型：">
          <a-select
            v-model="params.operationType"
            :options="operationTypeOptions"
            :field-names="operationTypeFieldNames"
            placeholder="请选择操作类型"
          />
        </a-form-item>
        <a-form-item field="methodType" label="请求方式：">
          <a-select
            v-model="params.methodType"
            :options="methodTypeOptions"
            :field-names="methodTypeFieldNames"
            placeholder="请选择请求方式"
            :style="{ width: '105px' }"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button
              v-permission="'log:operationlog:list'"
              type="primary"
              @click="handleSearch"
            >
              <template #icon>
                <icon-search />
              </template>
              {{ $t('searchTable.form.search') }}
            </a-button>
            <a-button type="primary" @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              {{ $t('searchTable.form.reset') }}
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-col>
  </a-row>
  <a-divider style="margin-top: 8px; margin-bottom: 16px" />
  <a-row style="flex: 1">
    <a-col :span="24" style="height: 100%">
      <a-table
        row-key="id"
        :loading="loading"
        :columns="columns"
        :scroll="{ y: 'calc(100vh - 596px)' }"
        :data="operationLogList"
        :bordered="false"
        :pagination="pagination"
        page-position="br"
        @page-change="handlePageNoChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #methodType="{ record }">
          <a-tag color="blue">
            {{ record.methodType }}
          </a-tag>
        </template>
        <template #status="{ record }">
          <a-tag
            v-if="record.status === 1"
            :color="record.status === 1 ? 'green' : 'red'"
          >
            {{ record.status === 1 ? '成功' : '失败' }}
          </a-tag>
          <a-tooltip v-else :content="record.exception">
            <a-tag
              style="cursor: pointer"
              :color="record.status === 1 ? 'green' : 'red'"
            >
              {{ record.status === 1 ? '成功' : '失败' }}
            </a-tag>
          </a-tooltip>
        </template>
        <template #operation="{ record }">
          <a-button
            v-permission="'log:operationlog:view'"
            type="text"
            @click="handleEdit(record)"
            >{{ $t('searchTable.operation.view') }}
          </a-button>
          <a-popconfirm
            :content="$t('modal.operation.tips')"
            @ok="handleDelete(record.key)"
          >
            <a-button v-permission="'log:operationlog:remove'" type="text"
              >{{ $t('searchTable.operation.remove') }}
            </a-button>
          </a-popconfirm>
        </template>
      </a-table>
    </a-col>
  </a-row>
</template>

<style scoped lang="less"></style>
